<?php
namespace app\beautiful\controller\miniapp\member\goods;
use app\BaseController;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\StoreGoodsModel;
use app\beautiful\model\order\StoreOrderModel;
use app\beautiful\model\logs\StoreWriteOffModel;
use app\beautiful\logic\MemberWalletLogic;
use think\facade\Db;

class Store extends BaseController{
    public function getStoreGoodsList()
    {
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
        ];
        //获取可用的商品id集合
        $goods_where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['is_open_yu','=',0],
        ];
        $goods_ids=GoodsModel::where($goods_where)->column('goods_id') ?? [];
        $where[]=['goods_id','in',$goods_ids];

        $order=['is_tui'=>'desc','fictitious_take_count'=>'desc','total_price'=>'asc'];
        $datas=StoreGoodsModel::with(['goods'=>function($query){
            $query->field('goods_id,name,cover_img');
        }])->where($where)
            ->order($order)
            ->field('store_goods_id,num,goods_id,total_price,worth,fictitious_take_count,gift_giving')
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select()
            ->append(['gift_total_price'])
            ->toArray();
        $return['datas']=$datas;

        return $this->success($return);

    }

    public function getStoreGoodsDetail()
    {

        $store_goods_id=$this->request->param('store_goods_id/d',0);
        //判断秒杀
        if(null === $store_goods = StoreGoodsModel::find($store_goods_id)) return $this->error('囤货不存在');
        if($store_goods->shop_id != $this->request->shopId) return $this->error('囤货不存在');
        if($store_goods->is_delete == 1) return $this->error('囤货不存在');
        if($store_goods->status != 1) return $this->error('囤货已下架');

        if(null === $goods = GoodsModel::find($store_goods->goods_id)) return $this->error('囤货商品不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('囤货商品不存在');
        if($goods->is_delete == 1) return $this->error('囤货商品不存在');
        if($goods->status != 1) return $this->error('囤货商品已下架');

        $store_goods->append(['gift_total_price']);

        $detail=[
            'store_goods_id'=>$store_goods_id,
            'goods'=>[
                'goods_id'=>$goods->goods_id,
                'rotation'=>$goods->rotation,
                'name'=>$goods->name,
                'goods_details'=>$goods->goods_details,
                'cover_img' => $goods->cover_img,
            ],
            'num'=>$store_goods->num,
            'total_price'=>$store_goods->total_price,
            'worth'=>$store_goods->worth,
            'gift_giving'=>$store_goods->gift_giving,
            'gift_total_price'=>$store_goods->gift_total_price,
            'fictitious_take_count'=>$store_goods->fictitious_take_count,
            'store_info'=>$store_goods->store_info,
        ];

        $return['detail']=$detail;

        return $this->success($return);

    }
    //余额支付
    public function moneyPay(){
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = StoreOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status != 1 || $order->is_delete == 1){
            return $this->error('订单不在未支付状态');
        }
        $time = time() - 900;//订单15分钟
        if($order->add_time < $time){ //如果 订单超过15分钟则不能支付了
            return $this->error('订单支付已经超时了，不能继续支付');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在'); 
        }
        Db::startTrans();
        try{
            $needPay = $order->need_pay;
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            $res = $MemberWalletLogic->useBalance($needPay, $order->total_price , 8); //商城购物使用
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            $order->is_paid = 1;
            $order->pay_time = time();
            $order->status =  4; //订单的状态值
            $order->pay_type = 'money';
            $order->save();            
            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    //获取囤货的
    public function getStoreOrderList(){
        $status = $this->request->param('status/d');
        $where = [
            ['shop_id','=', $this->request->shopId],
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0]
        ];
        switch ($status){ //查询订单的状态
            case 0: // 待付款
                $where[] = ['status','=',1];
                break;
            case 1://待自提
                $where[] = ['status','=',4];
                break;
            case 2://已完成  取消的订单也在已完成里面
                 $where[] = ['status','=',8];
                break;
            case 3:
                 $where[] = ['status','=',-1];
                break;
        }
         $datas = StoreOrderModel::where($where)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order(['store_order_id'=>'desc'])
            ->select()->hidden(['pay_info'])->append(['order_time','djs_time'])
            ->toArray();
        return $this->success([
            'list' => $datas
        ]);
    }
    //获取囤货订单的核销日志 没有分页
    public function getStoreOrderWriteOffLogs(){
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = StoreOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在'); 
        }
        $datas = StoreWriteOffModel::where([
            ['shop_id','=', $this->request->shopId],
            ['store_order_id','=',$order_id]
        ])->order(['store_write_off_id'=>'desc'])->select()->append(['add_time_format','operate_hidden_mobile'])->toArray();
        
        return $this->success([
            'list' => $datas
        ]);
    }
    
    //获取订单详情
    public  function getStoreOrderDetail(){
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = StoreOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在'); 
        }
        $order->hidden(['pay_info'])->append(['order_time','djs_time','pay_type_mean'])
            ->toArray();
        return $this->success([
            'detail' => $order
        ]);
    }
   
    public function  deleteOrder(){
         $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = StoreOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status !=8 && $order->status != -1){
            return $this->error('订单不允许删除');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在'); 
        }
        $order->is_delete = 1;
        $order->save();
        return $this->success('删除成功');
    }

    public function createOrder()
    {

        $goods=$this->request->param('goods/a',[]);
        $params=[
            'member_id'=>$this->request->memberId,
            'goods'=>$goods,
        ];
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_ids=$order_logic['store']->createOrder($params);
            Db::commit();
            return $this->success(['order_ids'=>$order_ids]);
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function cancelOrder()
    {
        $order_id=$this->request->param('order_id/d',0);
        $params=[
            'order_id'=>$order_id,
            'member_id'=>$this->request->memberId,
        ];
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic['store']->cancelOrder($params);
            Db::commit();
            return $this->success('成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
}
